<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 数据列表 -->
    <a-row class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden">
      <!-- 查询条件 -->
      <a-row class="w-full" v-if="showSearchRow">
        <a-form :model="searchForm" layout="inline" label-align="left" size="small">
          <a-form-item field="orderNumber" label="订单号">
            <a-input v-model="searchForm.orderNumber" placeholder="请输入订单号" />
          </a-form-item>
          <a-form-item field="berthNumber" label="泊位号">
            <a-input v-model="searchForm.berthNumber" placeholder="请输入泊位号" />
          </a-form-item>
          <a-form-item field="pointCharge" label="收费点">
            <a-input v-model="searchForm.pointCharge" placeholder="请输入收费点" />
          </a-form-item>
          <a-form-item field="plateNumber" label="车牌号">
            <a-input v-model="searchForm.plateNumber" placeholder="请输入车牌号" />
          </a-form-item>
          <a-form-item field="enterDate" label="驶入时间">
            <a-range-picker
              v-model="searchForm.enterDateRange"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择驶入时间范围"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item field="exitDate" label="驶离时间">
            <a-range-picker
              v-model="searchForm.exitDateRange"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择驶离时间范围"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
        <a-row justify="center" class="w-full mt-2">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon><icon-search /></template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
              content="确定删除选中订单吗?"
              type="warning"
              :popup-visible="deleteConfirmVisible"
              @ok="onDeleteConfirmOK"
              @cancel="onDeleteConfirmCancel"
            >
              <a-button
                type="primary"
                status="danger"
                @click="deleteBtnClick(selectedKeys)"
              >
                <template #icon><icon-delete /></template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon><icon-sync /></template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
            v-perm="['tc:order:add']"
            type="primary"
            size="small"
            @click="addBtnClick()"
          >
            <template #icon><icon-plus /></template>
            <template #default>添加</template>
          </a-button>

          <!-- 导入 -->
          <a-upload
            v-perm="['tc:order:add']"
            action="http://127.0.0.1:5173/minimalist/tc/order/importExcel"
            :show-file-list="false"
            :before-upload="beforeUpload"
            @success="handleImportSuccess"
            @error="handleImportError"
          >
            <a-button type="primary" status="success" size="small">
              <template #icon><icon-import /></template>
              <template #default>导入</template>
            </a-button>
          </a-upload>

          <!-- 导入模板下载 -->
          <a-button type="outline" size="small" @click="downloadTemplate">
            <template #icon><icon-download /></template>
            <template #default>下载模板</template>
          </a-button>
        </a-space>

        <!-- 其他按钮保持不变 -->
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon><icon-refresh /></template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button shape="circle" size="small" @click="showSearchRow = !showSearchRow">
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          class="w-[100%]"
          :scroll="{ minWidth: 600, y: '100%' }"
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          table-layout-fixed
          row-key="orderId"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
        >
          <template #orderNumber="{ record }">
            <a-link @click="detailBtnClick(record.orderId)" icon>{{
              record.orderNumber
            }}</a-link>
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-button
              v-perm="['tc:order:update']"
              type="text"
              size="mini"
              @click="updateBtnClick(record.orderId)"
            >
              <template #icon>
                <icon-edit />
              </template>
              <template #default>修改</template>
            </a-button>
            <a-popconfirm content="确认要删除吗?" @ok="deleteBtnOkClick(record.orderId)">
              <a-button
                v-perm="['tc:order:delete']"
                type="text"
                status="danger"
                size="mini"
              >
                <template #icon>
                  <icon-delete />
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
          v-if="datatable.total > 0"
          v-model:page-num="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="datatable.total"
          @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
      v-model:visible="modal.visible"
      :esc-to-close="false"
      :mask-closable="false"
      draggable
      width="1000px"
      :footer="false"
    >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        :params="modal.params"
        @ok="onOk"
        @cancel="onCancel"
        v-if="modal.visible"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, shallowRef } from "vue";
import { getPageListApi, deleteApi } from "~/api/tc/order.js";
import OrderDetail from "~/pages/tc/order/OrderDetail.vue";
import OrderEdit from "~/pages/tc/order/OrderEdit.vue";
import { Message } from "@arco-design/web-vue";
//全局实例
const { proxy } = getCurrentInstance();

// 上传前校验文件
const beforeUpload = (file) => {
  const isExcel =
    file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  if (!isExcel) {
    Message.error("只能上传Excel文件！");
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isLt2M) {
    Message.error("文件大小不能超过10MB！");
    return false;
  }

  return true;
};

// 导入成功处理
const handleImportSuccess = (res) => {
  // 检查响应数据结构
  if (res && res.data) {
    proxy.$msg.success(`成功导入${res.data.total || 0}条数据`);
    // 刷新列表
    getPageList(false);
  } else if (res && res.success) {
    // 兼容不同的响应格式
    proxy.$msg.success(`成功导入${res.total || 0}条数据`);
    // 刷新列表
    getPageList(false);
  } else {
    proxy.$msg.error(res?.message || res?.data?.message || "导入失败");
  }
};

// 导入失败处理
const handleImportError = (err) => {
  console.error("导入失败:", err);
  proxy.$msg.error("导入失败，请检查文件格式或网络连接");
};

// 下载导入模板
const downloadTemplate = () => {
  // 创建一个a标签用于下载
  const link = document.createElement("a");
  link.href = "/api/tc/order/downloadTemplate";
  link.setAttribute("download", "订单导入模板.xlsx");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

//加载字典
//是否展示搜索区域
const showSearchRow = ref(true);
//搜索参数表单
const searchForm = reactive({
  //订单号
  orderNumber: null,
  //泊位号
  berthNumber: null,
  //收费点
  pointCharge: null,
  //驶入时间范围
  enterDateRange: [],
  //驶离时间范围
  exitDateRange: [],
  //车牌号
  plateNumber: null,
  //页码
  pageNum: 1,
  //条数
  pageSize: 10,
});
//表格选中数据
const selectedKeys = ref([]);
//表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});
//数据列表
const datatable = reactive({
  //列配置
  columns: [
    {
      title: "订单号",
      dataIndex: "orderNumber",
      slotName: "orderNumber",
      align: "center",
    },
    {
      title: "泊位号",
      dataIndex: "berthNumber",
      align: "center",
    },
    {
      title: "收费点",
      dataIndex: "pointCharge",
      align: "center",
    },
    {
      title: "驶入时间",
      dataIndex: "enterDate",
      align: "center",
    },
    {
      title: "驶离时间",
      dataIndex: "exitDate",
      align: "center",
    },
    {
      title: "停留时长",
      dataIndex: "stayDate",
      align: "center",
    },
    {
      title: "车牌",
      dataIndex: "plateNumber",
      align: "center",
    },
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  //加载
  loading: false,
  //数据列表
  records: [],
  //总条数
  total: 0,
});
//查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.orderNumber = null;
    searchForm.berthNumber = null;
    searchForm.pointCharge = null;
    searchForm.enterDateRange = [];
    searchForm.exitDateRange = [];
    searchForm.plateNumber = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }

  // 处理日期范围，转换为后端需要的格式
  const params = { ...searchForm };

  if (params.enterDateRange && params.enterDateRange.length === 2) {
    params.enterStartDate = params.enterDateRange[0];
    params.enterEndDate = params.enterDateRange[1];
  }

  if (params.exitDateRange && params.exitDateRange.length === 2) {
    params.exitStartDate = params.exitDateRange[0];
    params.exitEndDate = params.exitDateRange[1];
  }

  // 删除前端使用的日期范围字段，避免传递给后端
  delete params.enterDateRange;
  delete params.exitDateRange;

  datatable.loading = true;
  getPageListApi(params)
    .then((res) => {
      datatable.records = res.records;
      datatable.total = res.total;
    })
    .finally(() => {
      datatable.loading = false;
    });
};
//公共模态框
const modal = reactive({
  //是否显示
  visible: false,
  //模态框标题
  title: "订单管理",
  //宽度
  width: "50%",
  //传递参数
  params: {},
  //组件名称
  component: null,
});
//添加按钮 -> 点击事件
const addBtnClick = () => {
  modal.visible = true;
  modal.title = "添加订单";
  modal.width = "400px";
  modal.params = { operationType: proxy.operationType.add.type };
  modal.component = shallowRef(OrderEdit);
};
//表格行数据 "查看" -> 点击
const detailBtnClick = (orderId) => {
  modal.visible = true;
  modal.title = "查看订单";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    orderId: orderId,
  };
  modal.component = shallowRef(OrderDetail);
};
//表格行数据 "修改" -> 点击
const updateBtnClick = (orderId) => {
  modal.visible = true;
  modal.title = "修改订单";
  modal.params = {
    operationType: proxy.operationType.update.type,
    orderId: orderId,
  };
  modal.component = shallowRef(OrderEdit);
};
//删除确认弹窗 -> 确认
const deleteConfirmVisible = ref(false);
//表格行数据 "删除" -> 点击
const deleteBtnClick = (selectedKeys) => {
  if (selectedKeys.length === 0) {
    proxy.$msg.error("请选择要删除的订单信息");
    return;
  }
  deleteConfirmVisible.value = true;
};
//表格行数据 "删除" -> 确认
const deleteBtnOkClick = (operatorLogId) => {
  deleteOperatorLogByOperatorLogIdApi(operatorLogId).then(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    //刷新列表
    getPageList();
  });
};
const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
  selectedKeys.value = [];
};
//删除确认弹窗 -> 确认
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;
  let userIds = [];
  selectedKeys.value.map((userId) => {
    userIds.push(userId);
  });
  deleteOperatorLogByOperatorLogIdsApi(userIds).then(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    //刷新列表
    selectedKeys.value = [];
    getPageList();
  });
};

const onOk = () => {
  modal.visible = false;
  //查询数据列表
  getPageList();
};
//模态框 -> 取消
const onCancel = () => {
  modal.visible = false;
};

//查询数据列表
getPageList();
</script>
<style scoped></style>
